/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.iwindplus.boot.domain.constant.CommonConstant;
import com.iwindplus.boot.domain.constant.CommonConstant.ExceptionConstant;
import com.iwindplus.boot.domain.constant.CommonConstant.FileConstant;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.MultipartBody.Builder;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.web.multipart.MultipartFile;

/**
 * Okhttp工具类.
 *
 * @author zengdegui
 * @since 2021/11/23
 */
@Slf4j
public class OkhttpUtil {

    private OkhttpUtil() {
        throw new IllegalStateException(CommonConstant.UTILITY_CLASS);
    }

    /**
     * get请求（参数拼接）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return Request
     */
    public static Request getQueryParamRequest(String url, Map<String, String> header, Map<String, Object> param) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        HttpUrl.Builder httpBuilder = OkhttpUtil.buildQueryParameter(url, param);
        return requestBuilder.url(httpBuilder.build()).get().build();
    }

    /**
     * post请求（FormBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return Request
     */
    public static Request postFormBodyRequest(String url, Map<String, String> header, Map<String, Object> param) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        final FormBody.Builder builder = OkhttpUtil.buildFormBody(param);
        return requestBuilder.url(url).post(builder.build()).build();
    }

    /**
     * post请求（MultipartBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @param files  文件集合（可选）
     * @return Request
     */
    public static Request postMultipartBodyRequest(String url, Map<String, String> header,
        Map<String, Object> param, List<MultipartFile> files) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        final Builder builder = OkhttpUtil.buildMultipartBody(param, files);
        return requestBuilder.url(url).post(builder.build()).build();
    }

    /**
     * post请求（json）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param json   参数（必填）
     * @return Request
     */
    public static Request postJsonRequest(String url, Map<String, String> header, String json) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        final RequestBody requestBody = RequestBody.create(json, MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE));
        return requestBuilder.url(url).post(requestBody).build();
    }

    /**
     * put请求（FormBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return Request
     */
    public static Request putFormBodyRequest(String url, Map<String, String> header, Map<String, Object> param) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        final FormBody.Builder builder = OkhttpUtil.buildFormBody(param);
        return requestBuilder.url(url).put(builder.build()).build();
    }

    /**
     * put请求（MultipartBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @param files  文件集合（可选）
     * @return Request
     */
    public static Request putMultipartBodyRequest(String url, Map<String, String> header,
        Map<String, Object> param, List<MultipartFile> files) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        final Builder builder = OkhttpUtil.buildMultipartBody(param, files);
        return requestBuilder.url(url).put(builder.build()).build();
    }

    /**
     * put请求（json）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param json   参数（必填）
     * @return Request
     */
    public static Request putJsonRequest(String url, Map<String, String> header, String json) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        final RequestBody requestBody = RequestBody.create(json, MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE));
        return requestBuilder.url(url).put(requestBody).build();
    }

    /**
     * delete请求（参数拼接）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return Request
     */
    public static Request deleteQueryParamRequest(String url, Map<String, String> header, Map<String, Object> param) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        HttpUrl.Builder httpBuilder = OkhttpUtil.buildQueryParameter(url, param);
        return requestBuilder.url(httpBuilder.build()).delete().build();
    }

    /**
     * delete请求（FormBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return Request
     */
    public static Request deleteFormBodyRequest(String url, Map<String, String> header, Map<String, Object> param) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        final FormBody.Builder builder = OkhttpUtil.buildFormBody(param);
        return requestBuilder.url(url).put(builder.build()).build();
    }

    /**
     * delete请求（json）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param json   参数（必填）
     * @return Request
     */
    public static Request deleteJsonRequest(String url, Map<String, String> header, String json) {
        final Request.Builder requestBuilder = OkhttpUtil.buildHeader(header);
        final RequestBody requestBody = RequestBody.create(json, MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE));
        return requestBuilder.url(url).delete(requestBody).build();
    }

    /**
     * 执行同步请求，同步响应结果.
     *
     * @param httpClient http客户端（必填）
     * @param request    请求（必填）
     * @return String
     */
    public static String executeRequest(OkHttpClient httpClient, Request request) {
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            if (Objects.nonNull(response) && response.isSuccessful() && Objects.nonNull(response.body())) {
                return response.body().string();
            }
        } catch (IOException ex) {
            log.error(ExceptionConstant.IO_EXCEPTION, ex);
        } finally {
            OkhttpUtil.closeResponse(response);
        }
        return null;
    }

    /**
     * 执行异步请求，异步响应结果.
     *
     * @param httpClient http客户端（必填）
     * @param request    请求（必填）
     * @param callback   回调
     */
    public static void executeRequestAsync(OkHttpClient httpClient, Request request, Callback callback) {
        httpClient.newCall(request).enqueue(callback);
    }

    /**
     * 关闭Response.
     *
     * @param response 响应
     */
    public static void closeResponse(Response response) {
        if (Objects.isNull(response)) {
            return;
        }
        response.close();
    }

    /**
     * 构造请求头.
     *
     * @param header 请求头
     * @return Request.Builder
     */
    public static Request.Builder buildHeader(Map<String, String> header) {
        final Request.Builder requestBuilder = new Request.Builder();
        if (MapUtil.isNotEmpty(header)) {
            requestBuilder.headers(Headers.of(header));
        }
        return requestBuilder;
    }

    private static HttpUrl.Builder buildQueryParameter(String url, Map<String, Object> param) {
        HttpUrl.Builder builder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (MapUtil.isEmpty(param)) {
            return builder;
        }
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            final Object value = entry.getValue();
            builder.addQueryParameter(entry.getKey(), Objects.nonNull(value) ? value.toString() : null);
        }
        return builder;
    }

    private static FormBody.Builder buildFormBody(Map<String, Object> param) {
        final FormBody.Builder builder = new FormBody.Builder();
        if (MapUtil.isEmpty(param)) {
            return builder;
        }
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            final Object value = entry.getValue();
            builder.add(entry.getKey(), Objects.nonNull(value) ? value.toString() : null);
        }
        return builder;
    }

    private static Builder buildMultipartBody(Map<String, Object> param, List<MultipartFile> multipartFiles) {
        Builder builder = new Builder().setType(MultipartBody.FORM);
        if (MapUtil.isNotEmpty(param)) {
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                final Object value = entry.getValue();
                builder.addFormDataPart(entry.getKey(), Objects.nonNull(value) ? value.toString() : null);
            }
        }
        if (CollUtil.isNotEmpty(multipartFiles)) {
            for (MultipartFile file : multipartFiles) {
                final RequestBody fileBody = RequestBody.Companion.create(FilesUtil.getBytes(file));
                builder.addFormDataPart(FileConstant.FILE, file.getOriginalFilename(), fileBody);
            }
        }
        return builder;
    }
}
